package com.example.no2.service;
import java.util.*;
import com.example.no2.vo.CategoryTreeVo;
import com.example.no2.mapper.AppCategoryMapper;
import com.example.no2.entity.AppCategory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
@Service
public class AppCategoryService {
    @Autowired
    AppCategoryMapper appCategoryDao;

    public CategoryTreeVo tree(){
        List<CategoryTreeVo> voList  =  new ArrayList<>();
        List<AppCategory> list = appCategoryDao.queryAll(new AppCategory());
        for (AppCategory category : list){
            CategoryTreeVo vo = new CategoryTreeVo();
            BeanUtils.copyProperties(category,vo);
            voList.add(vo);
        }
        CategoryTreeVo tree = new CategoryTreeVo();
        for (CategoryTreeVo categoryTreeVo : voList) {
            if (categoryTreeVo.getParentid()==null) {
                tree = findChildren(categoryTreeVo, voList);
            }
        }
        return tree;
    }

    private  CategoryTreeVo findChildren(CategoryTreeVo vo, List<CategoryTreeVo> voList){
        vo.setChildren(new ArrayList<>());
        for (CategoryTreeVo categoryTreeVo : voList) {
            if (vo.getId().equals(categoryTreeVo.getParentid())){
                vo.getChildren().add(categoryTreeVo);
                findChildren(categoryTreeVo,voList);
            }
        }
        return vo;
    }
}